<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊呗</title>
    <link rel="icon" href="data:,">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-image: url('/static/flowers.jpg');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            background-attachment: fixed;
            overflow: auto;
        }

        /* 猫咪图片样式 */
        .cat-groom {
            position: fixed;
            left: 20px;
            bottom: 20px;
            width: 120px;
            height: auto;
            z-index: 1000;
            cursor: pointer;
            transition: transform 0.3s ease;
        }
        
        .cat-groom:hover {
            transform: scale(1.1);
        }
        
        /* 小猫聊天对话框样式 */
        .cat-chat-container {
            position: fixed;
            left: 150px;
            bottom: 20px;
            width: 300px;
            height: 400px;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            display: none;
            flex-direction: column;
            z-index: 999;
            overflow: hidden;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.5);
        }
        
        .cat-chat-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 15px;
            background: rgba(26, 173, 25, 0.8);
            color: white;
        }
        
        .cat-chat-title {
            font-weight: bold;
            font-size: 16px;
            display: flex;
            align-items: center;
        }
        
        .cat-chat-title img {
            width: 24px;
            height: 24px;
            margin-right: 8px;
        }
        
        .cat-chat-close {
            cursor: pointer;
            font-size: 20px;
        }
        
        .cat-chat-messages {
            flex: 1;
            padding: 15px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        }
        
        .cat-message {
            margin-bottom: 10px;
            max-width: 80%;
            padding: 8px 12px;
            border-radius: 15px;
            word-wrap: break-word;
        }
        
        .cat-message-user {
            align-self: flex-end;
            background: rgba(0, 123, 255, 0.4);
            color: white;
            border-bottom-right-radius: 5px;
        }
        
        .cat-message-cat {
            align-self: flex-start;
            background: rgba(233, 236, 239, 0.7);
            color: #333;
            border-bottom-left-radius: 5px;
        }
        
        .cat-chat-form {
            display: flex;
            padding: 10px;
            background: rgba(240, 240, 240, 0.8);
            border-top: 1px solid rgba(200, 200, 200, 0.5);
        }
        
        .cat-chat-input {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-right: 8px;
        }
        
        .cat-chat-send {
            padding: 8px 15px;
            background: #1aad19;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        /* 添加打字动画效果 */
        .typing-indicator {
            display: flex;
            padding: 8px 12px;
            background: rgba(233, 236, 239, 0.4);
            border-radius: 15px;
            width: fit-content;
            margin-bottom: 10px;
            align-self: flex-start;
        }
        
        .typing-dot {
            width: 8px;
            height: 8px;
            background: #666;
            border-radius: 50%;
            margin: 0 2px;
            animation: typing-animation 1.5s infinite;
        }
        
        .typing-dot:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .typing-dot:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        @keyframes typing-animation {
            0%, 60%, 100% {
                transform: translateY(0);
                opacity: 0.5;
            }
            30% {
                transform: translateY(-5px);
                opacity: 1;
            }
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
        }

        #loginForm {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .room-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .room-card {
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            cursor: pointer;
            transition: transform 0.2s;
        }

        .room-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.15);
        }

        .room-name {
            font-size: 18px;
            font-weight: bold;
            color: #1a73e8;
            margin-bottom: 5px;
        }

        .room-info {
            font-size: 14px;
            color: #666;
            margin-bottom: 3px;
        }

        .room-description {
            font-size: 14px;
            color: #444;
            margin-top: 8px;
        }

        #chatRoom {
            display: none;
            background: transparent;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .chat-container {
            display: flex;
            height: 80vh;
            margin: 0;
            padding: 0;
            background: transparent;
            border-radius: 8px;
            position: relative;
        }

        .chat-main {
            flex: 1;
            display: flex;
            flex-direction: column;
            border-right: none;
            background: transparent;
        }

        #messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: transparent;
            border: none;
        }

        .chat-header {
            padding: 15px 20px;
            background: rgba(255, 255, 255, 0.2);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 40px;
            backdrop-filter: blur(5px);
        }

        .chat-header h2 {
            margin: 0;
            font-size: 16px;
            color: #333;
        }

        #messageForm {
            padding: 15px 20px;
            background: rgba(255, 255, 255, 0.2);
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            gap: 10px;
            height: 50px;
            backdrop-filter: blur(5px);
        }

        .chat-sidebar {
            width: 250px;
            background: rgba(255, 255, 255, 0.2);
            display: flex;
            flex-direction: column;
            border-left: 1px solid rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(5px);
            position: relative;
        }

        .online-users {
            flex: 0.5;
            overflow-y: auto;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .private-chats {
            flex: 0.5;
            overflow-y: auto;
        }

        .online-users-title, .private-chats-title {
            padding: 10px 15px;
            font-size: 14px;
            color: #333;
            background: rgba(255, 255, 255, 0.2);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(5px);
        }

        .chat-item {
            padding: 8px 15px;
            display: flex;
            align-items: center;
            cursor: pointer;
            background: rgba(255, 255, 255, 0.1);
            margin: 5px;
            border-radius: 4px;
        }

        .chat-item:hover {
            background: rgba(233, 233, 233, 0.4);
        }

        .chat-item.active {
            background: rgba(26, 173, 25, 0.2);
        }

        .chat-item-avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: #1aad19;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            font-size: 14px;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        .chat-item-info {
            flex: 1;
            overflow: hidden;
        }

        .chat-item-name {
            color: #333;
            font-size: 14px;
            margin-bottom: 2px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .chat-item-preview {
            color: #666;
            font-size: 12px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .unread-badge {
            background: #ff4d4f;
            color: white;
            border-radius: 10px;
            padding: 0 6px;
            font-size: 12px;
            margin-left: 5px;
            display: none;
        }

        .unread-badge.show {
            display: inline-block;
        }

        .user-list {
            padding: 10px 0;
        }

        .user-item {
            padding: 8px 15px;
            display: flex;
            align-items: center;
            cursor: pointer;
        }

        .user-item:hover {
            background: rgba(233, 233, 233, 0.4);
        }

        .user-item-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #1aad19;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            font-size: 16px;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        .user-item-avatar.tiger {
            background: #ff9800;
            color: #fff;
            font-size: 20px;
        }

        .user-item-avatar.fish {
            background: transparent;
            color: transparent;
            font-size: 20px;
        }

        .user-item-name {
            color: #333;
            font-size: 14px;
        }

        #messageInput {
            flex: 1;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            padding: 8px 12px;
            font-size: 14px;
        }

        #sendButton, #leaveButton {
            padding: 8px 20px;
            background: #1aad19;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        #leaveButton {
            background: #ff4d4f;
        }

        .message-container {
            margin-bottom: 15px;
            overflow: hidden;
            display: flex;
            align-items: flex-start;
            gap: 10px;
        }
        
        .message-container.right {
            flex-direction: row-reverse;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #1aad19;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            flex-shrink: 0;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        .message-avatar.tiger {
            background: #ff9800;
            color: #fff;
            font-size: 20px;
        }

        .message-avatar.fish {
            background: transparent;
            color: transparent;
            font-size: 20px;
        }

        .message-content-wrapper {
            display: flex;
            flex-direction: column;
            max-width: calc(70% - 50px);
        }

        .message {
            margin-bottom: 0;
            padding: 8px 12px;
            border-radius: 15px;
            word-wrap: break-word;
            width: fit-content;
        }

        .message-left {
            background: rgba(233, 236, 239, 0.4);
            float: left;
            clear: both;
            border-bottom-left-radius: 5px;
            backdrop-filter: blur(5px);
        }

        .message-right {
            background: rgba(0, 123, 255, 0.4);
            color: white;
            float: right;
            clear: both;
            border-bottom-right-radius: 5px;
            backdrop-filter: blur(5px);
        }

        .message-sender {
            font-size: 12px;
            color: #666;
            margin-bottom: 2px;
            margin-left: 12px;
        }

        .message-sender-right {
            text-align: right;
            margin-right: 12px;
        }

        .system-message {
            color: #666;
            font-style: italic;
            text-align: center;
            clear: both;
            float: none;
            background: none;
            margin: 10px auto;
            max-width: 100%;
            opacity: 1;
            transition: opacity 0.5s ease-in-out;
        }

        .system-message.fade-out {
            opacity: 0;
        }

        /* 音乐播放器样式 */
        .music-player {
            position: absolute;
            right: -280px;
            top: 0;
            width: 250px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            padding: 15px;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            height: fit-content;
            z-index: 1000;
        }

        .music-title {
            font-size: 14px;
            color: #333;
            margin-bottom: 10px;
            padding-bottom: 5px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }

        .music-list {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .music-item {
            display: flex;
            align-items: center;
            padding: 5px;
            border-radius: 4px;
            background: rgba(255, 255, 255, 0.1);
            cursor: pointer;
            transition: background 0.3s;
        }

        .music-item:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        .music-item.playing {
            background: rgba(26, 173, 25, 0.2);
        }

        .music-name {
            flex: 1;
            color: #333;
            font-size: 14px;
        }

        .music-controls {
            display: flex;
            gap: 10px;
        }

        .music-control-btn {
            background: none;
            border: none;
            color: #333;
            cursor: pointer;
            padding: 5px;
            font-size: 16px;
        }

        .music-control-btn:hover {
            color: #1aad19;
        }
    </style>
</head>
<body>
    <div class="container">
        <div id="loginForm">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <h2>可用聊天室</h2>
                <button id="logoutButton" style="padding: 8px 15px; background: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer;">登出</button>
            </div>
            <div class="room-list" id="roomList">
                <!-- 房间列表将通过JavaScript动态添加 -->
            </div>
        </div>

        <div id="chatRoom">
            <div class="chat-container">
                <div class="chat-main">
                    <div class="chat-header">
                        <h2><span id="roomName"></span></h2>
                        <input type="submit" id="leaveButton" value="退出群聊">
                    </div>
                    <div id="messages"></div>
                    <form id="messageForm">
                        <input type="text" id="messageInput" placeholder="请输入消息">
                        <input type="submit" id="sendButton" value="发送">
                    </form>
                </div>
                <div class="chat-sidebar">
                    <div class="online-users">
                        <div class="online-users-title">群成员 (<span id="onlineCount">0</span>)</div>
                        <div class="user-list" id="onlineUsersList">
                            <!-- 在线用户列表将通过JavaScript动态添加 -->
                        </div>
                        <!-- 音乐播放器 -->
                        <div class="music-player">
                            <div class="music-title">背景音乐</div>
                            <div class="music-list">
                                <div class="music-item" data-music="blackcloth.mp3">
                                    <span class="music-name">Black Cloth</span>
                                    <div class="music-controls">
                                        <button class="music-control-btn play-btn">▶️</button>
                                        <button class="music-control-btn stop-btn">⏹️</button>
                                    </div>
                                </div>
                                <div class="music-item" data-music="blackTone.mp3">
                                    <span class="music-name">Black Tone</span>
                                    <div class="music-controls">
                                        <button class="music-control-btn play-btn">▶️</button>
                                        <button class="music-control-btn stop-btn">⏹️</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- 添加私聊会话列表 -->
                    <div class="private-chats">
                        <div class="private-chats-title">私聊会话</div>
                        <div class="chat-list" id="privateChatsList">
                            <!-- 私聊会话列表将通过JavaScript动态添加 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加猫咪图片 -->
    <img src="/static/cat_groom.png" alt="猫咪" class="cat-groom" id="catImage">
    
    <!-- 添加小猫聊天对话框 -->
    <div class="cat-chat-container" id="catChatContainer">
        <div class="cat-chat-header">
            <div class="cat-chat-title">
                <img src="/static/cat_groom.png" alt="猫咪头像"> 
                <span>猫咪小助手</span>
            </div>
            <div class="cat-chat-close" id="catChatClose">×</div>
        </div>
        <div class="cat-chat-messages" id="catChatMessages">
            <!-- 默认欢迎消息 -->
            <div class="cat-message cat-message-cat">hey bro？</div>
        </div>
        <div class="cat-chat-form" id="catChatForm">
            <input type="text" class="cat-chat-input" id="catChatInput" placeholder="输入消息...">
            <button class="cat-chat-send" id="catChatSend">发送</button>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <script>
        const socket = io();
        let currentUsername = '';
        let currentRoom = '';
        let currentPrivateChat = null; // 当前私聊对象
        let privateChats = new Map(); // 存储私聊会话信息
        let unreadCounts = new Map(); // 存储未读消息计数

        // 音频控制
        let isEffectPlaying = false; // 音效播放状态
        let currentAudio = null; // 背景音乐控制
        let currentMusicItem = null;
        let musicList = [];
        let currentMusicIndex = 0;

        // 添加发送状态控制
        let isSending = false;

        // 添加群聊消息缓存
        let groupMessages = [];

        // 添加主会话未读消息计数
        let mainChatUnreadCount = 0;

        // 播放音效的函数
        async function playEffect(effectFile) {
            if (isEffectPlaying) return false;

            const effectAudio = new Audio(`/static/audios/${effectFile}`);
            
            // 如果是消息提示音，将音量调高
            if (effectFile === 'existingunread.mp3') {
                effectAudio.volume = 1.0; // 将提示音音量调整到最大（1.0）
            } else {
                effectAudio.volume = 0.5; // 其他音效保持较低音量
            }

            try {
                await new Promise((resolve, reject) => {
                    effectAudio.addEventListener('play', () => {
                        isEffectPlaying = true;
                    });
                    
                    effectAudio.addEventListener('ended', () => {
                        isEffectPlaying = false;
                        resolve();
                    });
                    
                    effectAudio.addEventListener('error', () => {
                        isEffectPlaying = false;
                        reject();
                    });
                    
                    effectAudio.play();
                });
                return true;
            } catch (error) {
                console.error('音效播放失败:', error);
                isEffectPlaying = false;
                return false;
            }
        }

        // 随机选择发送音频
        function getRandomSendAudio() {
            const sendAudios = ['send1.wav', 'send2.wav', 'send3.wav'];
            const randomIndex = Math.floor(Math.random() * sendAudios.length);
            return sendAudios[randomIndex];
        }

        // 初始化私聊
        function initializePrivateChat(targetUser) {
            const chatId = [currentUsername, targetUser.username].sort().join('_');
            
            if (!privateChats.has(chatId)) {
                privateChats.set(chatId, {
                    targetUser: {
                        username: targetUser.username,
                        avatar: targetUser.avatar
                    },
                    messages: []
                });
            }

            // 切换到私聊界面
            switchToPrivateChat(chatId);
            // 确保更新私聊列表，显示主会话
            updatePrivateChatsList();
        }

        // 切换到私聊
        function switchToPrivateChat(chatId) {
            currentPrivateChat = chatId;
            const messagesDiv = document.getElementById('messages');
            messagesDiv.innerHTML = '';

            // 显示私聊历史消息
            const chat = privateChats.get(chatId);
            if (chat) {
                chat.messages.forEach(msg => {
                    // 确保每条消息都有正确的头像
                    if (msg.username === currentUsername) {
                        const userData = JSON.parse(localStorage.getItem('chatUser'));
                        msg.avatar = userData.avatar;
                    } else {
                        msg.avatar = chat.targetUser.avatar;
                    }
                    displayMessage(msg);
                });

                // 清除未读消息计数
                unreadCounts.set(chatId, 0);
                // 立即更新UI以清除红点
                updatePrivateChatsList();
            }

            // 更新房间名显示
            const roomNameElement = document.getElementById('roomName');
            if (roomNameElement && chat) {
                const targetUser = chat.targetUser.username;
                roomNameElement.textContent = `与 ${targetUser} 私聊中`;
            }
        }

        // 切换回群聊
        function switchToGroupChat() {
            currentPrivateChat = null;
            const messagesDiv = document.getElementById('messages');
            messagesDiv.innerHTML = '';
            
            // 恢复群聊消息
            groupMessages.forEach(msg => {
                displayMessage(msg);
            });
            
            // 清除主会话未读计数
            mainChatUnreadCount = 0;
            
            // 更新UI状态，包括主会话
            updatePrivateChatsList();

            // 恢复房间名显示
            const roomNameElement = document.getElementById('roomName');
            if (roomNameElement) {
                roomNameElement.textContent = currentRoom;
            }
        }

        // 更新私聊列表
        function updatePrivateChatsList() {
            const chatsList = document.getElementById('privateChatsList');
            chatsList.innerHTML = '';

            // 添加主会话选项
            const mainChatItem = document.createElement('div');
            mainChatItem.className = 'chat-item';
            if (!currentPrivateChat) {
                mainChatItem.classList.add('active');
            }

            const mainAvatar = document.createElement('div');
            mainAvatar.className = 'chat-item-avatar';
            mainAvatar.textContent = currentRoom.charAt(0).toUpperCase();

            const mainInfo = document.createElement('div');
            mainInfo.className = 'chat-item-info';
            
            const mainName = document.createElement('div');
            mainName.className = 'chat-item-name';
            mainName.textContent = currentRoom;

            const mainPreview = document.createElement('div');
            mainPreview.className = 'chat-item-preview';
            const lastGroupMessage = groupMessages[groupMessages.length - 1];
            mainPreview.textContent = lastGroupMessage ? lastGroupMessage.message : '主会话';

            // 添加主会话未读消息提示
            const mainBadge = document.createElement('div');
            mainBadge.className = 'unread-badge';
            if (mainChatUnreadCount > 0) {
                mainBadge.classList.add('show');
                mainBadge.textContent = mainChatUnreadCount;
            }

            mainInfo.appendChild(mainName);
            mainInfo.appendChild(mainPreview);
            mainChatItem.appendChild(mainAvatar);
            mainChatItem.appendChild(mainInfo);
            mainChatItem.appendChild(mainBadge);

            mainChatItem.addEventListener('click', () => {
                switchToGroupChat();
            });

            // 添加主会话到列表最上方
            chatsList.appendChild(mainChatItem);

            // 添加分隔线
            const divider = document.createElement('div');
            divider.style.borderBottom = '1px solid rgba(255, 255, 255, 0.1)';
            divider.style.margin = '5px 0';
            chatsList.appendChild(divider);

            // 添加其他私聊会话
            privateChats.forEach((chat, chatId) => {
                const chatItem = document.createElement('div');
                chatItem.className = 'chat-item';
                chatItem.dataset.chatId = chatId;
                if (currentPrivateChat === chatId) {
                    chatItem.classList.add('active');
                }

                const avatar = document.createElement('div');
                avatar.className = 'chat-item-avatar';
                if (chat.targetUser.avatar === 'tiger') {
                    avatar.className += ' tiger';
                    avatar.innerHTML = '🐯';
                } else if (chat.targetUser.avatar === 'fish.png') {
                    avatar.style.backgroundImage = 'url("/static/fish.png")';
                } else if (chat.targetUser.avatar === 'star.jpg') {
                    avatar.style.backgroundImage = 'url("/static/star.jpg")';
                } else if (chat.targetUser.avatar === 'tiger1.png') {
                    avatar.style.backgroundImage = 'url("/static/tiger1.png")';
                } else if (chat.targetUser.avatar === 'cat.jpg') {
                    avatar.style.backgroundImage = 'url("/static/cat.jpg")';
                } else if (chat.targetUser.avatar === 'dog.png') {
                    avatar.style.backgroundImage = 'url("/static/dog.png")';
                } else {
                    avatar.textContent = chat.targetUser.username.charAt(0).toUpperCase();
                }

                const info = document.createElement('div');
                info.className = 'chat-item-info';
                
                const name = document.createElement('div');
                name.className = 'chat-item-name';
                name.textContent = chat.targetUser.username;

                const preview = document.createElement('div');
                preview.className = 'chat-item-preview';
                const lastMessage = chat.messages[chat.messages.length - 1];
                preview.textContent = lastMessage ? lastMessage.message : '暂无消息';

                const badge = document.createElement('div');
                badge.className = 'unread-badge';
                const unreadCount = unreadCounts.get(chatId) || 0;
                if (unreadCount > 0) {
                    badge.classList.add('show');
                    badge.textContent = unreadCount;
                }

                info.appendChild(name);
                info.appendChild(preview);
                chatItem.appendChild(avatar);
                chatItem.appendChild(info);
                chatItem.appendChild(badge);

                chatItem.addEventListener('click', () => {
                    switchToPrivateChat(chatId);
                });

                chatsList.appendChild(chatItem);
            });
        }

        // 检查登录状态
        document.addEventListener('DOMContentLoaded', function() {
            const savedUser = localStorage.getItem('chatUser');
            if (!savedUser) {
                window.location.href = '/';
                return;
            }

            const userData = JSON.parse(savedUser);
            currentUsername = userData.username;

            // 同时播放欢迎音效和加载UI
            playEffect('welcome.wav').catch(error => {
                console.error('播放欢迎音效失败:', error);
            });

            // 获取房间列表
            fetch('/api/rooms')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateRoomList(data.rooms);
                    }
                })
                .catch(error => {
                    console.error('Error fetching rooms:', error);
                });

            // 绑定发送表单事件
            const messageForm = document.getElementById('messageForm');
            messageForm.addEventListener('submit', function(e) {
                e.preventDefault();
                sendMessage(e);
            });

            // 绑定登出按钮事件
            const logoutButton = document.getElementById('logoutButton');
            logoutButton.addEventListener('click', logout);

            // 绑定退出群聊按钮事件
            const leaveButton = document.getElementById('leaveButton');
            if (leaveButton) {
                // 添加悬停音效
                leaveButton.addEventListener('mouseover', () => {
                    playEffect('back.wav');
                });

                // 添加点击事件
                leaveButton.addEventListener('click', async (e) => {
                    e.preventDefault();
                    await leave();
                });
            }

            // 初始化音乐播放器
            initMusicPlayer();
        });

        function logout() {
            localStorage.removeItem('chatUser');
            window.location.href = '/';
        }

        function updateRoomList(rooms) {
            const roomList = document.getElementById('roomList');
            if (!roomList) return;
            
            roomList.innerHTML = '';
            
            Object.entries(rooms).forEach(([roomId, room]) => {
                const roomCard = document.createElement('div');
                roomCard.className = 'room-card';
                
                roomCard.addEventListener('click', () => {
                    joinRoom(roomId, room.name);
                });
                
                roomCard.innerHTML = `
                    <div class="room-name">${room.name}</div>
                    <div class="room-info">创建者: ${room.created_by}</div>
                    <div class="room-info">创建时间: ${room.created_at}</div>
                    <div class="room-description">${room.description || '暂无描述'}</div>
                `;
                
                roomList.appendChild(roomCard);
            });
        }

        function joinRoom(roomId, roomName) {
            if (currentRoom) {
                socket.emit('leave', {
                    username: currentUsername,
                    room: currentRoom
                });
            }
            
            currentRoom = roomId;
            
            const loginForm = document.getElementById('loginForm');
            const chatRoom = document.getElementById('chatRoom');
            const roomNameElement = document.getElementById('roomName');
            const messagesDiv = document.getElementById('messages');
            
            if (loginForm) loginForm.style.display = 'none';
            if (chatRoom) chatRoom.style.display = 'block';
            if (roomNameElement) roomNameElement.textContent = roomName;
            if (messagesDiv) messagesDiv.innerHTML = '';
            
            // 清空群聊消息缓存
            groupMessages = [];
            
            // 初始化时立即更新私聊列表，显示主会话
            updatePrivateChatsList();
            
            socket.emit('join', {
                username: currentUsername,
                room: currentRoom
            });
        }

        async function leave() {
            // 如果是点击事件，先播放音效
            try {
                await playEffect('back.wav');
            } catch (error) {
                console.error('播放退出音效失败:', error);
            }
            
            socket.emit('leave', {
                username: currentUsername,
                room: currentRoom
            });
            
            // 清除所有私聊会话
            privateChats.clear();
            unreadCounts.clear();
            currentPrivateChat = null;
            
            // 重置UI
            document.getElementById('loginForm').style.display = 'block';
            document.getElementById('chatRoom').style.display = 'none';
            document.getElementById('messages').innerHTML = '';
            document.getElementById('privateChatsList').innerHTML = '';
            currentRoom = '';

            // 重新获取房间列表
            fetch('/api/rooms')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateRoomList(data.rooms);
                    }
                })
                .catch(error => {
                    console.error('Error fetching rooms:', error);
                });
        }

        socket.on('message', function(data) {
            if (currentRoom !== data.room) {
                return;
            }

            // 保存群聊消息到缓存
            groupMessages.push(data);

            // 如果当前在私聊中，增加主会话未读计数并播放提示音
            if (currentPrivateChat && data.username !== currentUsername) {
                playEffect('existingunread.mp3');
                mainChatUnreadCount++;
                updatePrivateChatsList();
            } else if (!currentPrivateChat) {
                displayMessage(data);
            }
        });

        socket.on('user_joined', function(data) {
            console.log('User joined:', data.username);
            if (data.users) {
                updateOnlineUsers(data.users);
            }
        });

        socket.on('user_left', function(data) {
            console.log('User left:', data.username);
            if (data.users) {
                updateOnlineUsers(data.users);
            }
        });

        socket.on('kicked', function(data) {
            alert(data.message);
            document.getElementById('loginForm').style.display = 'block';
            document.getElementById('chatRoom').style.display = 'none';
            document.getElementById('messages').innerHTML = '';
            currentRoom = '';
        });

        socket.on('rooms_update', function(rooms) {
            if (document.getElementById('loginForm').style.display === 'block') {
                updateRoomList(rooms);
            }
        });

        function updateOnlineUsers(users) {
            if (!users) return;
            
            const usersList = document.getElementById('onlineUsersList');
            const onlineCount = document.getElementById('onlineCount');
            
            if (!usersList || !onlineCount) return;
            
            usersList.innerHTML = '';
            const userArray = Object.values(users);
            onlineCount.textContent = userArray.length;
            
            userArray.forEach(userData => {
                if (!userData || !userData.username) return;
                
                const userItem = document.createElement('div');
                userItem.className = 'user-item';
                
                const avatar = document.createElement('div');
                avatar.className = 'user-item-avatar';
                
                try {
                    if (userData.avatar === 'tiger') {
                        avatar.className += ' tiger';
                        avatar.innerHTML = '🐯';
                    } else if (userData.avatar === 'fish.png') {
                        avatar.style.backgroundImage = 'url("/static/fish.png")';
                    } else if (userData.avatar === 'star.jpg') {
                        avatar.style.backgroundImage = 'url("/static/star.jpg")';
                    } else if (userData.avatar === 'tiger1.png') {
                        avatar.style.backgroundImage = 'url("/static/tiger1.png")';
                    } else if (userData.avatar === 'cat.jpg') {
                        avatar.style.backgroundImage = 'url("/static/cat.jpg")';
                    } else if (userData.avatar === 'dog.png') {
                        avatar.style.backgroundImage = 'url("/static/dog.png")';
                    } else {
                        avatar.textContent = userData.username.charAt(0).toUpperCase();
                    }

                    const name = document.createElement('div');
                    name.className = 'user-item-name';
                    name.textContent = userData.username;
                    
                    // 只为非当前用户添加点击事件
                    if (userData.username !== currentUsername) {
                        // 添加音效播放和私聊初始化
                        const handleUserClick = () => {
                            playEffect('side.wav');
                            initializePrivateChat(userData);
                        };
                        
                        // 为头像和用户项添加事件
                        avatar.addEventListener('mouseover', () => playEffect('side.wav'));
                        avatar.addEventListener('click', handleUserClick);
                        userItem.addEventListener('click', handleUserClick);
                    } else {
                        // 为当前用户添加标识
                        const nameText = document.createElement('span');
                        nameText.textContent = ' (我)';
                        nameText.style.color = '#1aad19';
                        name.appendChild(nameText);
                    }
                    
                    userItem.appendChild(avatar);
                    userItem.appendChild(name);
                    usersList.appendChild(userItem);
                } catch (error) {
                    console.error('Error creating user item:', error);
                }
            });
        }

        // 音乐播放器控制
        function playNextMusic() {
            if (!musicList.length) return;
            
            // 获取下一首歌的索引
            currentMusicIndex = (currentMusicIndex + 1) % musicList.length;
            const nextItem = musicList[currentMusicIndex];
            
            // 模拟点击播放按钮
            nextItem.querySelector('.play-btn').click();
        }

        function initMusicPlayer() {
            musicList = Array.from(document.querySelectorAll('.music-item'));
            if (!musicList.length) return;
            
            musicList.forEach((item, index) => {
                const playBtn = item.querySelector('.play-btn');
                const stopBtn = item.querySelector('.stop-btn');
                const musicFile = item.dataset.music;

                playBtn.addEventListener('click', () => {
                    if (currentAudio && currentMusicItem === item) {
                        // 如果点击的是当前音乐，切换暂停/播放状态
                        if (currentAudio.paused) {
                            // 如果是暂停状态，继续播放
                            currentAudio.play().catch(error => {
                                console.error('播放音乐失败:', error);
                            });
                            item.classList.add('playing');
                            playBtn.textContent = '⏸️';
                        } else {
                            // 如果是播放状态，暂停
                            currentAudio.pause();
                            item.classList.remove('playing');
                            playBtn.textContent = '▶️';
                        }
                    } else {
                        // 停止当前播放的音乐（如果有）
                        if (currentAudio) {
                            currentAudio.pause();
                            currentMusicItem.classList.remove('playing');
                            currentMusicItem.querySelector('.play-btn').textContent = '▶️';
                        }

                        // 播放新的音乐
                        const audio = new Audio(`/static/audios/${musicFile}`);
                        audio.loop = false; // 关闭单曲循环
                        audio.volume = 0.8; // 设置背景音乐音量为0.8
                        
                        // 添加播放结束事件，自动播放下一首
                        audio.addEventListener('ended', playNextMusic);
                        
                        // 预加载音频
                        audio.addEventListener('canplaythrough', () => {
                            audio.play().catch(error => {
                                console.error('播放音乐失败:', error);
                            });
                            currentAudio = audio;
                            currentMusicItem = item;
                            currentMusicIndex = index;
                            item.classList.add('playing');
                            playBtn.textContent = '⏸️';
                        });

                        // 加载音频
                        audio.load();
                    }
                });

                stopBtn.addEventListener('click', () => {
                    if (currentAudio && currentMusicItem === item) {
                        currentAudio.pause();
                        currentAudio.currentTime = 0;
                        currentAudio = null;
                        currentMusicItem = null;
                        item.classList.remove('playing');
                        playBtn.textContent = '▶️';
                    }
                });
            });

            // 等待DOM完全加载后再自动播放第一首歌
            setTimeout(() => {
                const firstSong = musicList[0];
                if (firstSong) {
                    const audio = new Audio(`/static/audios/${firstSong.dataset.music}`);
                    audio.loop = false;
                    audio.volume = 0.8; // 设置背景音乐音量为0.8
                    audio.addEventListener('ended', playNextMusic);
                    
                    // 预加载音频
                    audio.addEventListener('canplaythrough', () => {
                        audio.play().catch(error => {
                            console.error('自动播放音乐失败:', error);
                        });
                        currentAudio = audio;
                        currentMusicItem = firstSong;
                        currentMusicIndex = 0;
                        firstSong.classList.add('playing');
                        firstSong.querySelector('.play-btn').textContent = '⏸️';
                    });

                    // 加载音频
                    audio.load();
                }
            }, 500);
        }

        // 修改私聊消息处理
        socket.on('private_message', function(data) {
            const chatId = [data.from, data.to].sort().join('_');
            
            // 如果是新的私聊，初始化会话
            if (!privateChats.has(chatId)) {
                privateChats.set(chatId, {
                    targetUser: {
                        username: data.from === currentUsername ? data.to : data.from,
                        avatar: data.fromAvatar
                    },
                    messages: []
                });
            }

            // 确保使用正确的头像
            const messageData = {
                username: data.from,
                message: data.message,
                timestamp: new Date().toLocaleTimeString(),
                isPrivate: true,
                avatar: data.from === currentUsername ? 
                    JSON.parse(localStorage.getItem('chatUser')).avatar : 
                    data.fromAvatar
            };

            // 更新消息记录
            const chat = privateChats.get(chatId);
            if (chat) {
                chat.messages.push(messageData);
                
                // 只有在收到其他用户的消息时才显示和播放提示音
                if (data.from !== currentUsername) {
                    // 播放提示音
                    playEffect('existingunread.mp3');
                    
                    // 如果当前正在查看这个私聊，直接显示消息
                    if (currentPrivateChat === chatId) {
                        displayMessage(messageData);
                    } else {
                        // 否则增加未读计数
                        const unreadCount = (unreadCounts.get(chatId) || 0) + 1;
                        unreadCounts.set(chatId, unreadCount);
                    }
                }
                
                updatePrivateChatsList();
            }
        });

        // 修改消息显示函数
        function displayMessage(data) {
            const messagesDiv = document.getElementById('messages');
            const messageContainer = document.createElement('div');
            messageContainer.className = 'message-container';
            
            if (data.username === 'System') {
                const messageElement = document.createElement('div');
                messageElement.className = 'message system-message';
                messageElement.textContent = data.message;
                messageContainer.appendChild(messageElement);
                messagesDiv.appendChild(messageContainer);
                
                setTimeout(() => {
                    messageElement.classList.add('fade-out');
                    setTimeout(() => {
                        if (messageContainer && messageContainer.parentNode) {
                            messageContainer.remove();
                        }
                    }, 500);
                }, 5000);
            } else {
                if (data.username === currentUsername) {
                    messageContainer.className += ' right';
                }

                const avatarElement = document.createElement('div');
                avatarElement.className = 'message-avatar';

                if (data.avatar === 'tiger') {
                    avatarElement.className += ' tiger';
                    avatarElement.innerHTML = '🐯';
                } else if (data.avatar === 'fish.png') {
                    avatarElement.style.backgroundImage = 'url("/static/fish.png")';
                } else if (data.avatar === 'star.jpg') {
                    avatarElement.style.backgroundImage = 'url("/static/star.jpg")';
                } else if (data.avatar === 'tiger1.png') {
                    avatarElement.style.backgroundImage = 'url("/static/tiger1.png")';
                } else if (data.avatar === 'cat.jpg') {
                    avatarElement.style.backgroundImage = 'url("/static/cat.jpg")';
                } else if (data.avatar === 'dog.png') {
                    avatarElement.style.backgroundImage = 'url("/static/dog.png")';
                } else {
                    avatarElement.textContent = data.username.charAt(0).toUpperCase();
                }

                const contentWrapper = document.createElement('div');
                contentWrapper.className = 'message-content-wrapper';

                const senderElement = document.createElement('div');
                senderElement.className = 'message-sender' + (data.username === currentUsername ? ' message-sender-right' : '');
                senderElement.textContent = data.username + (data.isPrivate ? ' (私聊)' : '');
                contentWrapper.appendChild(senderElement);

                const messageElement = document.createElement('div');
                messageElement.className = 'message ' + (data.username === currentUsername ? 'message-right' : 'message-left');
                messageElement.textContent = data.message;
                contentWrapper.appendChild(messageElement);

                messageContainer.appendChild(avatarElement);
                messageContainer.appendChild(contentWrapper);
                messagesDiv.appendChild(messageContainer);
            }
            
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        // 修改发送消息函数
        async function sendMessage(e) {
            if (e) e.preventDefault();
            if (isSending) return; // 如果正在发送，直接返回
            
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value.trim();
            
            if (!message) return;
            
            isSending = true; // 设置发送状态
            
            try {
                // 播放随机发送音效并等待完成
                const audioFile = getRandomSendAudio();
                const audioPlayed = await playEffect(audioFile);
                
                // 如果音效播放失败，也允许发送消息
                if (currentPrivateChat) {
                    // 发送私聊消息
                    const [user1, user2] = currentPrivateChat.split('_');
                    const targetUsername = user1 === currentUsername ? user2 : user1;
                    
                    // 获取当前用户的头像信息
                    const userData = JSON.parse(localStorage.getItem('chatUser'));
                    
                    // 构建消息数据
                    const messageData = {
                        username: currentUsername,
                        message: message,
                        timestamp: new Date().toLocaleTimeString(),
                        isPrivate: true,
                        avatar: userData.avatar
                    };

                    // 更新本地消息记录并显示
                    const chat = privateChats.get(currentPrivateChat);
                    if (chat) {
                        chat.messages.push(messageData);
                        displayMessage(messageData);
                        updatePrivateChatsList();
                    }

                    // 发送消息到服务器
                    socket.emit('private_message', {
                        to: targetUsername,
                        from: currentUsername,
                        message: message,
                        chatId: currentPrivateChat,
                        fromAvatar: userData.avatar
                    });
                } else {
                    // 发送群聊消息
                    socket.emit('message', {
                        username: currentUsername,
                        message: message,
                        room: currentRoom
                    });
                }
                
                messageInput.value = '';
            } catch (error) {
                console.error('发送消息时发生错误:', error);
            } finally {
                // 立即重置发送状态
                isSending = false;
            }
        }

        // 猫咪聊天功能
        document.addEventListener('DOMContentLoaded', function() {
            const catImage = document.getElementById('catImage');
            const catChatContainer = document.getElementById('catChatContainer');
            const catChatClose = document.getElementById('catChatClose');
            const catChatForm = document.getElementById('catChatForm');
            const catChatInput = document.getElementById('catChatInput');
            const catChatMessages = document.getElementById('catChatMessages');
            
            // 猫咪对话状态
            let isCatTyping = false;
            
            // 猫咪点击事件
            catImage.addEventListener('click', function() {
                // 播放音效
                playEffect('side.wav');
                // 显示对话框
                catChatContainer.style.display = 'flex';
                // 聚焦到输入框
                catChatInput.focus();
            });
            
            // 关闭对话框
            catChatClose.addEventListener('click', function() {
                catChatContainer.style.display = 'none';
            });
            
            // 发送消息到猫咪
            catChatForm.addEventListener('submit', function(e) {
                e.preventDefault();
                sendMessageToCat();
            });
            
            // 点击发送按钮
            document.getElementById('catChatSend').addEventListener('click', function() {
                sendMessageToCat();
            });
            
            // 添加Enter键发送功能
            catChatInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessageToCat();
                }
            });
            
            // 添加打字动画
            function showTypingIndicator() {
                if (isCatTyping) return;
                
                isCatTyping = true;
                const typingIndicator = document.createElement('div');
                typingIndicator.className = 'typing-indicator';
                typingIndicator.id = 'typingIndicator';
                
                for (let i = 0; i < 3; i++) {
                    const dot = document.createElement('div');
                    dot.className = 'typing-dot';
                    typingIndicator.appendChild(dot);
                }
                
                catChatMessages.appendChild(typingIndicator);
                catChatMessages.scrollTop = catChatMessages.scrollHeight;
            }
            
            // 隐藏打字动画
            function hideTypingIndicator() {
                const indicator = document.getElementById('typingIndicator');
                if (indicator) {
                    indicator.remove();
                }
                isCatTyping = false;
            }
            
            // 发送消息给猫咪
            async function sendMessageToCat() {
                const message = catChatInput.value.trim();
                if (!message) return;
                
                // 显示用户消息
                addCatChatMessage(message, 'user');
                catChatInput.value = '';
                
                try {
                    // 播放随机发送音效
                    const audioFile = getRandomSendAudio();
                    await playEffect(audioFile);
                    
                    // 显示猫咪正在输入
                    showTypingIndicator();
                    
                    // 发送请求到后端
                    const response = await fetch('/api/cat_chat', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            message: message,
                            username: currentUsername
                        })
                    });
                    
                    const data = await response.json();
                    
                    // 隐藏打字动画
                    hideTypingIndicator();
                    
                    if (data.success) {
                        // 显示猫咪回复
                        addCatChatMessage(data.message, 'cat');
                    } else {
                        // 显示错误消息
                        addCatChatMessage(data.message || '我好像遇到了一些问题...', 'cat');
                    }
                } catch (error) {
                    console.error('与猫咪聊天时发生错误:', error);
                    
                    // 隐藏打字动画
                    hideTypingIndicator();
                    
                    // 显示错误消息
                    addCatChatMessage('网络似乎出现了问题...', 'cat');
                }
            }
            
            // 添加消息到猫咪聊天界面
            function addCatChatMessage(message, sender) {
                const messageElement = document.createElement('div');
                messageElement.className = `cat-message cat-message-${sender}`;
                messageElement.textContent = message;
                
                catChatMessages.appendChild(messageElement);
                catChatMessages.scrollTop = catChatMessages.scrollHeight;
            }
        });
    </script>
</body>
</html> 